package com.xy.service.common;

import com.xy.api.model.dto.common.FieldOptionDTO;
import com.xy.api.service.common.IFieldOptionService;
import com.xy.mapper.common.FieldOptionMapper;
import com.xy.model.po.common.FieldOptionPO;
import com.xy.utils.CustomBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Random;

@Service
public class FieldOptionServiceImpl implements IFieldOptionService {

    @Autowired
    private FieldOptionMapper fieldOptionMapper;

    @Override
    public String generateOptionKey(String preCode) {
        if (!StringUtils.hasText(preCode)) {
            throw new IllegalArgumentException("参数异常");
        }
        boolean optionKeyExist = false;
        String optionKey;
        do {
            long currentTimeMillis = System.currentTimeMillis();
            Random random = new Random();
            int randomNum = random.nextInt(9000) + 1000;
            optionKey = String.format("%s_%s_%s", preCode, currentTimeMillis, randomNum);

            List<FieldOptionPO> fieldOptionList = fieldOptionMapper.findFieldOptionList(optionKey);
            if (!CollectionUtils.isEmpty(fieldOptionList)) {
                optionKeyExist = true;
            }
        } while (optionKeyExist);
        return optionKey;
    }

    @Override
    public void batchInsert(List<FieldOptionDTO> fieldOptionList) {
        if (CollectionUtils.isEmpty(fieldOptionList)) {
            return;
        }
        List<FieldOptionPO> fieldOptionPOS = CustomBeanUtil.copyListProperties(fieldOptionList, FieldOptionPO::new);
        fieldOptionMapper.batchInsert(fieldOptionPOS);
    }
}
